//
//  ProjectController.swift
//  baihuiju
//
//  Created by 赵家彬 on 2018/5/23.
//  Copyright © 2018年 赵家彬. All rights reserved.
//

import UIKit
import MJRefresh
import RxSwift
import RxCocoa

class ProjectController: CBBaseViewController {

    var arrProject:[ProjectModel] = [ProjectModel]()
    
    @IBOutlet weak var tbProject: UITableView!
    let CELL_ID = "PROJECT_CELL_ID"
    var param:[String:Any]? = nil
    var tips:String = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "项目"
        tbProject.register(UINib(nibName: "ProjectCell", bundle: nil), forCellReuseIdentifier: CELL_ID)
        tbProject.rowHeight = 341 * suitParm
        tbProject.mj_header = MJRefreshNormalHeader(refreshingBlock: { [weak self] in
            self?.initData()
        })
        
        tbProject.mj_header.beginRefreshing()
        
        NotificationCenter.default.rx
            .notification(NSNotification.Name.init(rawValue: "Flush_Project_List"))
            .subscribe(onNext: { [weak self] notification in
                self?.tbProject.setContentOffset(CGPoint(x: 0, y: 0), animated: false)
                self?.tbProject.mj_header.beginRefreshing()
            }).disposed(by: disposeBag)
    }
    
    func initData() {
        NetworkTool.requestData(url: ActionURL.GET_PRODUCT_TIPS, param: nil)
            .map { (json) -> String in
                return json["rows"].dictionaryValue["remark"]?.stringValue ?? ""
            }.catchErrorJustReturn("")
            .observeOn(MainScheduler.instance)
            .subscribe(onNext:{ [unowned self] strTips in
                self.tips = strTips
            }).disposed(by: disposeBag)
        
        NetworkTool.requestData(url: ActionURL.GET_PRODUCT_DATA, param: param)
            .map { (json) -> [ProjectModel]? in
                var tmpArrModel = [ProjectModel]()
                for tpjson in (json["rows"].dictionaryValue["data"]?.arrayValue) ?? [] {
                    let tmpModel = ProjectModel()
                    tmpModel.id = tpjson["id"].stringValue
                    tmpModel.number = tpjson["number"].stringValue
                    tmpModel.img = tpjson["img"].stringValue
                    tmpModel.name = tpjson["name"].stringValue
                    tmpModel.amount = tpjson["amount"].stringValue
                    tmpModel.buy_amount = tpjson["buy_amount"].stringValue
                    tmpModel.pro_num = tpjson["pro_num"].stringValue
                    tmpModel.progress_status = tpjson["progress_status"].stringValue
                    tmpModel.remark = tpjson["remark"].stringValue
                    tmpModel.tick_count_time = tpjson["tick_count_time"].stringValue
                    
                    var arrTpPackage = [PackageModel]()
                    let allKeyValue = tpjson["goods_id"].arrayValue.first?.dictionaryValue ?? [:]
                    for key in allKeyValue.keys {
                        let tpPackage = PackageModel()
                        tpPackage.type = key
                        tpPackage.arrCommodity = CommodityModel.mj_objectArray(withKeyValuesArray: allKeyValue[key]?.arrayObject) as? [CommodityModel] ?? [CommodityModel]()
                        arrTpPackage.append(tpPackage)
                    }
                    arrTpPackage.sort(by: { (model1, model2) -> Bool in
                        return model1.type.compare(model2.type).rawValue < 0
                    })
                    arrTpPackage.first?.isSelect = true
                    tmpModel.arrPackage = arrTpPackage
                    tmpArrModel.append(tmpModel)
                }
                return tmpArrModel
            }.catchErrorJustReturn(nil)
            .observeOn(MainScheduler.instance)
            .subscribe(onNext:{ [unowned self] arrOpModel in
                self.tbProject.mj_header.endRefreshing()
                if let arrModel = arrOpModel {
                    self.arrProject = arrModel
                    self.tbProject.reloadData()
                }
            }).disposed(by: disposeBag)
    }

}

extension ProjectController: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return arrProject.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:ProjectCell = (tableView.dequeueReusableCell(withIdentifier: CELL_ID, for: indexPath) as? ProjectCell) ?? ProjectCell()
        cell.model = arrProject[indexPath.row]
        return cell
    }
    
}
